package tech.senri.iot.socket.service.socket

import com.fasterxml.jackson.databind.ObjectMapper
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.util.AttributeKey
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component
import tech.senri.iot.socket.config.RedisMQConfig
import tech.senri.iot.socket.model.ResponseMessage


@Component
@ChannelHandler.Sharable
class ServerChannelHandler : SimpleChannelInboundHandler<ResponseMessage>()
{
    private val log = LoggerFactory.getLogger(this.javaClass)

    @Autowired
    private lateinit var template: StringRedisTemplate

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    override fun channelRead0(ctx: ChannelHandlerContext, msg: ResponseMessage?)
    {
        msg?.let {
            msg.deviceId?.let { SessionManager.setSession(it, ctx.channel()) }
            template.convertAndSend(RedisMQConfig.device_message_response, objectMapper.writeValueAsString(msg))
        }
    }

    override fun channelUnregistered(ctx: ChannelHandlerContext)
    {
        super.channelUnregistered(ctx)
        log.info(String.format("# client unregistered... : %s", ctx.channel()))
    }

    override fun channelRegistered(ctx: ChannelHandlerContext)
    {
        super.channelRegistered(ctx)
        log.info(String.format("# client registered...：   %s ...", ctx.channel()))
        val session = DeviceSession(channel = ctx.channel())
    }

}
